package org.example.flea_market_mvc.controller;

import org.example.flea_market_mvc.entity.Categories;
import org.example.flea_market_mvc.param.CategoryParam;
import org.example.flea_market_mvc.service.categories.CategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/categories")
@Validated
public class CategoriesController {

    @Autowired
    private CategoriesService categoriesService;

    @PostMapping
    public ApiResponse<String> addCategory(@Valid @RequestBody CategoryParam categoryParam) {
        int result = categoriesService.insert(categoryParam);
        return result > 0 ? ApiResponse.success("添加分类成功") : ApiResponse.error(400, "添加分类失败");
    }

    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteCategory(@PathVariable Integer id) {
        int result = categoriesService.deleteById(id);
        return result > 0 ? ApiResponse.success("删除分类成功") : ApiResponse.notFound("分类不存在");
    }

    @PutMapping
    public ApiResponse<String> updateCategory(@Valid @RequestBody CategoryParam categoryParam) {
        int result = categoriesService.update(categoryParam);
        return result > 0 ? ApiResponse.success("修改分类成功") : ApiResponse.notFound("分类不存在");
    }

    @GetMapping("/{id}")
    public ApiResponse<Categories> getCategory(@PathVariable Integer id) {
        Categories category = categoriesService.selectById(id);
        return category != null ? ApiResponse.success(category) : ApiResponse.notFound("分类不存在");
    }

    @GetMapping
    public ApiResponse<List<Categories>> getAllCategories() {
        List<Categories> categories = categoriesService.selectAll();
        return ApiResponse.success(categories);
    }

    @GetMapping("/page")
    public ApiResponse<org.example.flea_market_mvc.entity.PageInfo<Categories>> getCategoriesPage(CategoryParam param) {
        org.example.flea_market_mvc.entity.PageInfo<Categories> pageInfo = categoriesService.selectPage(param);
        return ApiResponse.success(pageInfo);
    }
}